package com.msb.apipassenger.service;

import com.msb.commons.constant.CommonStatusEnum;
import com.msb.commons.constant.TokenConstant;
import com.msb.commons.response.ResponseResult;
import com.msb.commons.response.TokenResponse;
import com.msb.commons.response.TokenResult;
import com.msb.commons.util.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: chshh
 * @version: 1.0
 */
@Service
public class TokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshToken){
        //是否为空
        TokenResult tokenResult = JwtUtils.parseToken(refreshToken);
        if(tokenResult == null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //读取redis中的refreshToken
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();

        String refreshTokenKey = TokenConstant.REFRESH_TOKEN_TYPE+phone+identity;
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        //校验token
        if((StringUtils.isBlank(refreshTokenRedis)) || (!refreshToken.trim().equals(refreshTokenRedis.trim()))){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //生成双token
        String refreshToken1 = JwtUtils.generatorToken(phone, identity, TokenConstant.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone, identity, TokenConstant.ACCESS_TOKEN_TYPE);

        String accessTokenKey = TokenConstant.ACCESS_TOKEN_TYPE+phone+identity;

        //放入redis中
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken1,31, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setRefreshToken(refreshToken);
        tokenResponse.setAccessToken(accessToken);

        return ResponseResult.success(tokenResponse);
    }
}